import React, { useEffect, useState } from 'react';
import TitleBar from '@/src/components/titleBar';
import Taro, { useDidShow } from '@tarojs/taro';
import { View } from '@tarojs/components';
import store from '@/src/store';
import CigarItem from '@/src/components/cigarItem';
import { collectionListFun } from '@/src/common/method/wikiFun';
import InfiniteScroll from '@/src/components/infiniteScroll';
import LoadingSpinner from '@/src/components/loadingSpinner';
import BottomContainer from '@/src/components/bottomContainer';
import './index.less';
import CommonBlank from '@/src/components/pageBlank';
import { observer } from 'mobx-react-lite';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
//我的-商品收藏
const productCollect = () => {
  const pageNum = 10;
  const [dataList, setDataList] = useState<any>([]);
  const [loadingText, setLoadingText] = useState<any>('加载中');
  const [maxPageNum, setMaxPageNum] = useState<number>(0);
  const [pageIndex, setPageIndex] = useState<number>(1);
  // 一级下拉刷新状态
  const [refresherTriggered, setRefresherTriggered] = useState(false);
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  //获取商品收藏
  const getList = (pageIndex: any) => {
    collectionListFun({
      ucUserId: Taro.getStorageSync('userId'),
      pageNo: pageIndex,
      pageSize: 10,
    }).then((res: any) => {
      setLoadingText('');
      setMaxPageNum(Math.ceil(res.totalCount / pageNum));
      let result: any = [];
      if (pageIndex === 1) {
        result = [...res.list];
      } else {
        result = [...dataList, ...res.list];
      }

      const processed =
        result &&
        result.map((item: any) => ({
          ...item,
          select: false,
        }));
      setDataList(processed);
    });
  };
  //首次进入页面获取第一页列表
  useEffect(() => {
    getList(pageIndex);
  }, []);
  //跳转到商品详情
  const detailClick = (sku: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({
      url: `/subPagesWiki/cigaDetail/index?sku=${sku}`,
    });
  };

  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    const index = pageIndex + 1;
    if (index > maxPageNum) {
      return false;
    }
    setPageIndex(index);
    setLoadingText('加载中...');
    return getList(index);
  };

  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
  };

  //列表内容
  const content = () => {
    return (
      <View>
        {dataList &&
          dataList.map((item: any, index: any) => {
            return (
              <CigarItem
                key={index}
                data={item}
                gotoDetail={(sku: any) => detailClick(sku)}
              />
            );
          })}
      </View>
    );
  };
  // 一级下拉刷新处理
  const handleRefreshFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    setRefresherTriggered(true);
    //是否是首次下拉刷新
    getList(pageIndex);
    setTimeout(() => {
      setRefresherTriggered(false);
    }, 1000);
  };
  // 顶部
  const { windowHeight, screenWidth } = Taro.getSystemInfoSync();
  const rpx2px = (rpx: number) => (rpx / 750) * screenWidth;
  const contentPx =
    windowHeight -
    rpx2px(store.commonStore.safeAreaTop) -
    store.commonStore.safeAreaBottom;
  return (
    <View
      className={`mine-product-collection mine-product-collection-${store.commonStore.isIos}`}
      style={{
        paddingTop: `${store.commonStore.pageAreaTop}rpx`,
      }}
    >
      <TitleBar title="商品收藏" showLeftBack={true} />
      <View
        className="mine-publish-content"
        style={{ marginBottom: `${store.commonStore.safeAreaBottom}rpx` }}
      >
        {/* 头部导航 */}
        <View className="mine-publish-content-header">
          <InfiniteScroll
            style={{ height: `${contentPx}px` }}
            hasMore={pageIndex < maxPageNum}
            loadMore={() => loadMore()}
            refresherTriggered={refresherTriggered}
            handleRefresh={() => handleRefreshFun()}
            dataList={dataList}
            loading={loadingText === '' ? false : true}
            content={content()}
          />
          <CommonBlank
            visible={dataList && dataList.length === 0}
            desc="暂无收藏"
            blank={
              'https://file.linkcook.cn/image/wineMiniProgram/exception/empty_content.png'
            }
          />
          <BottomContainer />
        </View>
      </View>
      <LoadingSpinner text={loadingText} />
    </View>
  );
};

export default observer(productCollect);
